package com.client.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.client.common.R;
import com.client.pojo.FlowerUser;
import com.client.service.FlowerUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 晚云
 * @since 2023-09-12
 */
@CrossOrigin
@RestController
@RequestMapping("/flower-user")
public class FlowerUserController {

    @Autowired
    private FlowerUserService flowerUserService;

    /**
     * 获取验证码
     * @return
     */
    @GetMapping("/code")
    public R code(){
        Random r = new Random();
        String code = "";
        for (int i = 1; i < 7; i++) {
            code += r.nextInt(10);
        }
        return R.success(code);
    }

    /**
     * 用户注册方法
     * @param flowerUser
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody FlowerUser flowerUser) {
        flowerUser.setUserPhone(flowerUser.getUserAccount());
        if (flowerUser.getUserSex().equals(1)){
            flowerUser.setUserSex("男");
        }else {
            flowerUser.setUserSex("女");
        }
        FlowerUser one = flowerUserService.getOne(Wrappers.<FlowerUser>lambdaQuery().eq(FlowerUser::getUserAccount, flowerUser.getUserAccount()));
        boolean flag = false;
        if (one == null){
            flag = flowerUserService.save(flowerUser);
        }
        if (flag) {
            return R.success(flag,"注册成功！");
        }
        return R.error("注册失败!");
    }

    /**
     * 用户登录
     * @param flowerUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody FlowerUser flowerUser){
        flowerUser.setUserPhone(flowerUser.getUserAccount());
        String userId = flowerUserService.selectByAccountAndPassWord(flowerUser);
        if (userId != null){
            return R.success(userId,"登录成功！");
        }else {
            return R.error("登录失败！");
        }
    }

}

